package org.rain.core.mp.log;

import org.apache.ibatis.logging.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定义日志打印类
 */
public class MyLogbackImpl implements Log {

    Logger log = LoggerFactory.getLogger("sql");
    private final String formatLevel;
    private final Boolean isPrint;
    private final Boolean isPrintResult;

    final static String BOLD = "\u001B[1m";
    final static String GREEN = "\u001B[32m";
    final static String BLUE = "\u001B[34m";
    final static String RESET = "\u001B[0m";


    public MyLogbackImpl(String level) {
        //是否应该打印SQL日志
        this.isPrint = level.startsWith("org.rain");
        //是否应该打印SQL执行结果
        this.isPrintResult = false;

        if (level.length() > 56) {
            level = shortenPackage(level);
        }
        this.formatLevel = String.format("%-60s", level);
    }

    @Override
    public boolean isDebugEnabled() {
        return true;
    }

    @Override
    public boolean isTraceEnabled() {
        return true;
    }

    @Override
    public void error(String s, Throwable e) {
        log.error(s);
        e.printStackTrace(System.err);
    }

    @Override
    public void error(String s) {
        log.error(s);
    }

    @Override
    public void debug(String s) {
        if (isPrint) {
            if (s.startsWith("==>  Preparing")) {
                log.debug("{} :: {}{}{}{}{}", formatLevel, BOLD, GREEN, s, RESET, RESET);
            } else {
                log.debug("{} :: {}{}{}", formatLevel, BLUE, s, RESET);
            }
        }
    }

    @Override
    public void trace(String s) {
        if (isPrintResult) {
            log.trace(s);
        }
    }

    @Override
    public void warn(String s) {
        log.warn(s);
    }

    private String shortenPackage(String fullName) {
        // 拆分成路径
        String[] parts = fullName.split("\\.");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < parts.length; i++) {
            // 最后两个通常是关键类和方法，不缩写
            if (i >= parts.length - 2) {
                sb.append(parts[i]);
                if (i != parts.length - 1) {
                    sb.append(".");
                }
            } else {
                sb.append(parts[i].charAt(0)).append('.');
            }
        }
        return sb.toString();
    }
}
